import React from 'react';
import { Table, Card, Button, Space, message, Modal } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { userService } from '../services/userService';
import UserForm from '../components/UserForm';

const Users = () => {
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [formVisible, setFormVisible] = React.useState(false);
  const [currentUser, setCurrentUser] = React.useState(null);
  const [formMode, setFormMode] = React.useState('create');

  // 加载用户列表
  const loadUsers = async () => {
    try {
      setLoading(true);
      const data = await userService.getUsers();
      setUsers(data);
    } catch (error) {
      console.error('加载用户列表失败:', error);
      message.error('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    loadUsers();
  }, []);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setFormMode('create');
    setCurrentUser(null);
    setFormVisible(true);
  };

  const handleEdit = (record) => {
    setFormMode('edit');
    setCurrentUser(record);
    setFormVisible(true);
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除用户 ${record.username} 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await userService.deleteUser(record.id);
          message.success('删除成功');
          loadUsers();
        } catch (error) {
          console.error('删除用户失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  const handleFormSuccess = () => {
    setFormVisible(false);
    loadUsers();
  };

  return (
    <Card
      title="用户管理"
      extra={
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          添加用户
        </Button>
      }
    >
      <Table
        loading={loading}
        columns={columns}
        dataSource={users}
        rowKey="id"
        pagination={{
          total: users.length,
          pageSize: 10,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />
      <UserForm
        visible={formVisible}
        mode={formMode}
        initialValues={currentUser}
        onCancel={() => setFormVisible(false)}
        onSuccess={handleFormSuccess}
      />
    </Card>
  );
};

export default Users;